//
//  ONAlertViewController.m
//  Volatix
//
//  Created by Anh Tran on 6/3/14.
//  Copyright (c) 2014 Familly. All rights reserved.
//

#import "ONAlertViewController.h"
#import "ONRealTimeSectionView.h"
// Views
//#import "ONAlertSectionView.h"
#import "ONAlertTableViewCell.h"
#import "ONObjectAlert.h"
#import "SWTableViewCell.h"
#import "ONSettingsViewController.h"
#import "ONAddSymbolViewController.h"
@interface ONAlertViewController ()<SWTableViewCellDelegate>
@property (nonatomic) BOOL useCustomCells;
@end

@implementation ONAlertViewController


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Do any additional setup after loading the view.
    _settingArray=[APP_DELEGATE getingDataSymbleForTypeScreen:2];//[[NSMutableArray alloc] init];
   if(_settingArray==nil)
   {
       _settingArray=[[NSMutableArray alloc] init];
   }
    [self updateDateAlertSaving:false];
    self.useCustomCells = NO;
    [self startPullDownRefresh];
    [self initBaseColumnData];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(clickDone) name:SAVING_DATA_ALERT object:nil];
}
#pragma mark - CLICK DONE DELEGATE
-(void)clickDone
{
    
    NSLog(@"%s",__FUNCTION__);
    [self updateDateAlertSaving:true];
    
    
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [Utils setTypeScreen:3];
    [Utils setMainScreen:true];/// need it for saving
    self.filerData =[NSMutableArray arrayWithArray:[APP_DELEGATE getingFilterTimerForTypeScreen:3]];
    [self.tableView reloadData];
}
-(BOOL)isInVisibleArray:(ONObjectAlert *)item
{
    for (int index=0; index<[self.filerData count]; index++) {
        ONObjectAlert *_obj=[self.filerData objectAtIndex:index];
       
        if([item.symbleName isEqualToString:_obj.symbleName]&&item.Type==_obj.Type)
        {
            return true;
        }
    }
    
    return false;
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    // Get current controller
    if ([self.navigationController.visibleViewController isKindOfClass:[ONAddSymbolViewController class]]) {
        
        ONAddSymbolViewController *controller = (ONAddSymbolViewController *)self.navigationController.visibleViewController;
        controller.addSymbolItemsArray = _settingArray;
        controller.typeScreen=2;
        // current data
        controller.currentRealTimeData =[[NSMutableArray alloc]init];
        for ( ONISOObjects *oNISOObject in _settingArray) {
            [controller.currentRealTimeData addObject:oNISOObject];
        }
        
    } else if ([self.navigationController.visibleViewController isKindOfClass:[ONSettingsViewController class]]) {
        
       ONSettingsViewController *controller = (ONSettingsViewController *)self.navigationController.visibleViewController;
        controller.dataArray=self.dataArray;
        
    }
    
    // Set Image
}



-(void)updateDateAlertSaving:(BOOL)value
{
    
    
    if(self.dataArray==nil)
    {
        self.dataArray = [[NSMutableArray alloc] init];
    }
    else
    {
        NSMutableArray *temp=[[NSMutableArray alloc] init];
        for (int index=0; index<[self.dataArray count]; index++) {
            ///
            ONObjectAlert * item =[self.dataArray objectAtIndex:index];
            if(item.IsAutoAdd)
            {
                [temp addObject:item];
            }
        }
        self.dataArray =[NSMutableArray arrayWithArray:temp];
       
    }
    NSMutableArray *dataRealtime=[APP_DELEGATE getingDataSymbleForTypeScreen:0];
    NSMutableArray *dataDayAhead=[APP_DELEGATE getingDataSymbleForTypeScreen:1];
    
    for (int index=0; index<[dataRealtime count]; index++) {
        ONISOObjects *_obj = [dataRealtime objectAtIndex:index];
        ONObjectAlert *itemAdd =[[ONObjectAlert alloc] init];
        itemAdd.symbleName =[NSString stringWithFormat:@"%@",_obj.name];
        itemAdd.Type=0; /// realtime
        itemAdd.IsAutoAdd=NO;
        [self.dataArray addObject:itemAdd];
    }
    for (int index=0; index<[dataDayAhead count]; index++) {
        ONISOObjects *_obj = [dataDayAhead objectAtIndex:index];
        ONObjectAlert *itemAdd =[[ONObjectAlert alloc] init];
        itemAdd.symbleName =[NSString stringWithFormat:@"%@",_obj.name];
        itemAdd.Type=1; /// dayAhead
        itemAdd.IsAutoAdd=NO;
        [self.dataArray addObject:itemAdd];

    }
    /// alert View Setting
    
    NSMutableArray *alertSetting = [NSMutableArray arrayWithArray:_settingArray];
    for (int index=0; index<[alertSetting count]; index++) {
        ONISOObjects *_obj = [alertSetting objectAtIndex:index];
        ONObjectAlert *itemAdd =[[ONObjectAlert alloc] init];
        itemAdd.symbleName =[NSString stringWithFormat:@"%@",_obj.name];
        itemAdd.Type=-1; /// not setting
        itemAdd.IsAutoAdd=NO;
        [self.dataArray addObject:itemAdd];
    }

   //Saving Alert Setting
    if(value)
    {
        [APP_DELEGATE savingDataSymble:alertSetting andTypeScreen:2];
    }
    
    
    [self.tableView reloadData];
}


-(void)initBaseColumnData
{
    if(self.columnArray==nil){
        self.columnArray = [[NSMutableArray alloc]init];
    }
    for (int i=0; i<4; i++)
    {
        ONColumnTitleObject *column = [[ONColumnTitleObject alloc]init];
        column.allowToSelect = NO;
        column.mainColumn=1;
        switch (i) {
            case 0:
                column.name = @"Point";
                break;
            case 1:
                column.name = @"Type";
                break;
            case 2:
                column.name = @"Trigger";
                break;
            case 3:
                column.name = @"Status";
                break;
            default:
                break;
        }
        [self.columnArray addObject:column];
        
        
    }
    [self.columnArray sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        ONColumnTitleObject *p1 = (ONColumnTitleObject*)obj1;
        ONColumnTitleObject *p2 = (ONColumnTitleObject*)obj2;
        
        if (p1.mainColumn < p2.mainColumn) {
            return (NSComparisonResult)NSOrderedDescending;
        }
        
        if (p1.mainColumn > p2.mainColumn) {
            return (NSComparisonResult)NSOrderedAscending;
        }
        return (NSComparisonResult)NSOrderedSame;
        
        
    }];
    
    
}

#pragma mark - UITableViewDataSource Methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    NSInteger numberOfCell = [self.dataArray count];
    return numberOfCell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 44;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    return ([self isInVisibleArray:[self.dataArray objectAtIndex:indexPath.row]])?0:44;
    
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    UIView *sectionView = [[UIView alloc]init];
    sectionView.backgroundColor = [UIColor clearColor];
    
    CGFloat currentX = 0;
    
    for (int i=0; i<[self.columnArray count]; i++) {
        
        ONRealTimeSectionView *view = [[ONRealTimeSectionView alloc]initWithFrame:CGRectMake(0, 0, kWidthColumn, kHeightSection)];
        ONColumnTitleObject *column =[self.columnArray objectAtIndex:i];
        //NSLog(@"column.name  %@",column.name);
        view.titleLabel.text = column.name;
        
        currentX = i*kWidthColumn;
        
        view.frame = CGRectMake(currentX, 0, kWidthColumn, kHeightSection);
        sectionView.frame = CGRectMake(0, 0, currentX + kWidthColumn, kHeightSection);
        
        [sectionView addSubview:view];
    }
    
    return sectionView;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    NSString *reuseIdentifier = @"ONAlertTableViewCell";
    
    ONAlertTableViewCell *cell = (ONAlertTableViewCell*)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = (ONAlertTableViewCell *)[[[NSBundle mainBundle] loadNibNamed:reuseIdentifier owner:self options:nil] objectAtIndex:0];
    }
    
    ONObjectAlert *_obj = [self.dataArray objectAtIndex:indexPath.row];
    [cell loadCellData:_obj];
    cell.delegate = self;
    cell.rightUtilityButtons=[self rightButtons];
    
    return cell;
   
}




- (NSArray *)rightButtons
{
    NSMutableArray *rightUtilityButtons = [NSMutableArray new];
    [rightUtilityButtons sw_addUtilityButtonWithColor:
     [UIColor colorWithRed:0.78f green:0.78f blue:0.8f alpha:1.0]
                                                title:@"More"];
    [rightUtilityButtons sw_addUtilityButtonWithColor:
     [UIColor colorWithRed:1.0f green:0.231f blue:0.188 alpha:1.0f]
                                                title:@"Delete"];
    
    return rightUtilityButtons;
}


#pragma mark - SWTableViewDelegate

- (void)swipeableTableViewCell:(SWTableViewCell *)cell scrollingToState:(SWCellState)state
{
    switch (state) {
        case 0:
            NSLog(@"utility buttons closed");
            break;
        case 1:
            NSLog(@"left utility buttons open");
            break;
        case 2:
            NSLog(@"right utility buttons open");
            break;
        default:
            break;
    }
}

- (void)swipeableTableViewCell:(SWTableViewCell *)cell didTriggerLeftUtilityButtonWithIndex:(NSInteger)index
{
    switch (index) {
        case 0:
            NSLog(@"left button 0 was pressed");
            break;
        case 1:
            NSLog(@"left button 1 was pressed");
            break;
        case 2:
            NSLog(@"left button 2 was pressed");
            break;
        case 3:
            NSLog(@"left btton 3 was pressed");
        default:
            break;
    }
}

- (void)swipeableTableViewCell:(SWTableViewCell *)cell didTriggerRightUtilityButtonWithIndex:(NSInteger)index
{
    switch (index) {
        case 0:
        {
            NSLog(@"More button was pressed");
//            UIAlertView *alertTest = [[UIAlertView alloc] initWithTitle:@"Hello" message:@"More more more" delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles: nil];
//            [alertTest show];
//            
//            [cell hideUtilityButtonsAnimated:YES];
            break;
        }
        case 1:
        {
            // Delete button was pressed
//            NSIndexPath *cellIndexPath = [self.tableView indexPathForCell:cell];
//            
//            [_testArray[cellIndexPath.section] removeObjectAtIndex:cellIndexPath.row];
//            [self.tableView deleteRowsAtIndexPaths:@[cellIndexPath] withRowAnimation:UITableViewRowAnimationLeft];
            break;
        }
        default:
            break;
    }
}

- (BOOL)swipeableTableViewCellShouldHideUtilityButtonsOnSwipe:(SWTableViewCell *)cell
{
    // allow just one cell's utility button to be open at once
    return YES;
}

- (BOOL)swipeableTableViewCell:(SWTableViewCell *)cell canSwipeToState:(SWCellState)state
{
    switch (state) {
        case 1:
            // set to NO to disable all left utility buttons appearing
            return YES;
            break;
        case 2:
            // set to NO to disable all right utility buttons appearing
            return YES;
            break;
        default:
            break;
    }
    
    return YES;
}




#pragma mark - UITableViewDelegate Methods

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // Deselect the row
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark - Webservice Methods

// when pull down refresh, this method will be called
- (void)requestGetData {
    // hardcode
    [self performSelector:@selector(doneLoadingTableViewData) withObject:nil afterDelay:1];
}
-(void)dealloc
{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:SAVING_DATA_ALERT object:nil];
}
@end
//- (NSArray *)leftButtons
//{
//    NSMutableArray *leftUtilityButtons = [NSMutableArray new];
//
//    [leftUtilityButtons sw_addUtilityButtonWithColor:
//     [UIColor colorWithRed:0.07 green:0.75f blue:0.16f alpha:1.0]
//                                                icon:[UIImage imageNamed:@"check.png"]];
//    [leftUtilityButtons sw_addUtilityButtonWithColor:
//     [UIColor colorWithRed:1.0f green:1.0f blue:0.35f alpha:1.0]
//                                                icon:[UIImage imageNamed:@"clock.png"]];
//    [leftUtilityButtons sw_addUtilityButtonWithColor:
//     [UIColor colorWithRed:1.0f green:0.231f blue:0.188f alpha:1.0]
//                                                icon:[UIImage imageNamed:@"cross.png"]];
//    [leftUtilityButtons sw_addUtilityButtonWithColor:
//     [UIColor colorWithRed:0.55f green:0.27f blue:0.07f alpha:1.0]
//                                                icon:[UIImage imageNamed:@"list.png"]];
//
//    return leftUtilityButtons;
//}